/**
 * Created by Foold on 2014-5-2.
 */

var ztreeObj;
var nodeStatus = {};
var openStatus = {};
var idinfo={};
$(function(){
    var settings = {
        view:{
            dblClickExpand: false
        },
        data: {
            simpleData: {
                enable: true
            }
        },
        check: {
            enable: true,
            chkboxType :{ "Y" : "s", "N" : "s" }

        },
        callback: {
            onDblClick: zTreeOnDblClick,
            onClick:zTreeOnClick
        }
    };

    var roots = [
        {
            name : "北方特种能源有限公司西安庆华公司",
            open : false,
            nocheck:true,
            id:"root",
            isParent:true
        }
    ];
    ztreeObj = $.fn.zTree.init($("#userTree") , settings ,roots);
    var root = ztreeObj.getNodes();
    zTreeOnClick(event,"userTree",root[0]);
});

function zTreeOnDblClick(event, treeId, treeNode) {
    if(treeNode.isParent==true) return;
    userofchat({name:treeNode.id,localName:treeNode.name});
}

function zTreeOnClick(event,treeId,treeNode){
    if(nodeStatus[treeNode.tId] || treeNode.isParent==false){
        ztreeObj.expandNode(treeNode,openStatus[treeNode.id]);
        openStatus[treeNode.id]=!openStatus[treeNode.id];
        return ;
    }

    socket.emit('ztreeNode', treeNode.id);
    idinfo[treeNode.id] = treeNode.tId;
}

socket.on("ztreeNode",function(data){
    //console.log('treeNode is is sent ');
    var tId = idinfo[data['treeId']];
    if(!tId)return;

    var node = ztreeObj.getNodeByTId(tId);
    //console.log(node.isParent);
    if(nodeStatus[node.tId])return;
    nodeStatus[node.tId]=true;
    if(!node)return;
    //console.log(data.treeNodes);
    ztreeObj.removeChildNodes(node);
    ztreeObj.addNodes(node,data.treeNodes,true);
    ztreeObj.expandNode(node);
    openStatus[node.id]=true;
});
